<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="900px"
    :before-close="handleClose"
    class="unified-dialog queue-config-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon" :class="headerIconClass">
          <el-icon><component :is="headerIcon" /></el-icon>
        </div>
        <div class="header-content">
          <h3>{{ dialogTitle }}</h3>
          <p>{{ dialogDescription }}</p>
        </div>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      label-position="left"
      class="queue-config-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>基础信息</span>
        </div>

        <el-form-item label="环境" prop="env_id">
          <el-select
            v-model="form.env_id"
            placeholder="选择环境"
            :disabled="isViewMode || isEditMode"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option
              v-for="env in envList"
              :key="env.id"
              :label="env.env_name"
              :value="env.id"
            />
          </el-select>
          <span class="form-tip" v-if="!isViewMode && isEditMode">环境创建后不可修改</span>
        </el-form-item>

        <el-form-item label="队列Key" prop="queue_key">
          <el-input
            v-model="form.queue_key"
            placeholder="请输入队列key"
            :disabled="isViewMode || isEditMode"
            clearable
          />
          <span class="form-tip" v-if="!isViewMode && isEditMode">队列Key创建后不可修改</span>
        </el-form-item>

        <el-form-item label="队列类型" prop="queue_type">
          <el-select
            v-model="form.queue_type"
            placeholder="选择队列类型"
            :disabled="isViewMode"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option label="list" value="list" />
            <el-option label="zset" value="zset" />
            <el-option label="set" value="set" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-input
            v-model="form.category"
            placeholder="请输入分类"
            :disabled="isViewMode"
            clearable
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息（可选）"
            :disabled="isViewMode"
            clearable
          />
        </el-form-item>
      </div>

      <!-- 监控设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><View /></el-icon>
          <span>监控设置</span>
        </div>

        <el-form-item label="启用监控" prop="is_monitored">
          <div class="switch-container">
            <el-switch
              v-model="form.is_monitored"
              :active-value="1"
              :inactive-value="0"
              :disabled="isViewMode"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">监控数据收集</p>
              <p class="description-text">启用后将定时扫描队列并收集统计数据</p>
            </div>
          </div>
        </el-form-item>
      </div>

      <!-- 告警设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Bell /></el-icon>
          <span>告警设置</span>
        </div>

        <el-form-item label="启用告警" prop="is_alert_enabled">
          <div class="switch-container">
            <el-switch
              v-model="form.is_alert_enabled"
              :active-value="1"
              :inactive-value="0"
              :disabled="isViewMode"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">告警通知</p>
              <p class="description-text">启用后当触发告警条件时会发送通知</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="Webhook地址" prop="webhook_url">
          <el-input
            v-model="form.webhook_url"
            placeholder="企业微信/钉钉Webhook地址（可选）"
            :disabled="isViewMode"
            clearable
          />
          <span class="form-tip">留空则使用系统默认配置</span>
        </el-form-item>

        <el-form-item label="长度过高告警" prop="alert_on_length_high">
          <el-radio-group v-model="form.alert_on_length_high" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">队列长度超过阈值时告警</span>
        </el-form-item>

        <el-form-item label="增长激增告警" prop="alert_on_growth_surge">
          <el-radio-group v-model="form.alert_on_growth_surge" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">队列增长超过阈值时告警</span>
        </el-form-item>

        <el-form-item label="增长下降告警" prop="alert_on_growth_drop">
          <el-radio-group v-model="form.alert_on_growth_drop" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">队列下降超过阈值时告警</span>
        </el-form-item>

        <el-form-item label="空队列告警" prop="alert_on_empty">
          <el-radio-group v-model="form.alert_on_empty" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">队列为空时告警</span>
        </el-form-item>

        <el-form-item label="失败率过高告警" prop="alert_on_failed_rate_high">
          <el-radio-group v-model="form.alert_on_failed_rate_high" :disabled="isViewMode">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <span class="form-tip">失败率超过阈值时告警</span>
        </el-form-item>
      </div>

      <!-- 阈值配置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Setting /></el-icon>
          <span>阈值配置</span>
        </div>

        <el-form-item label="长度阈值" prop="length_threshold">
          <el-input-number
            v-model="form.length_threshold"
            :min="0"
            :max="100000000"
            :step="10000"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">队列长度阈值，默认1000000</span>
        </el-form-item>

        <el-form-item label="增长率阈值(%)" prop="growth_rate_threshold">
          <el-input-number
            v-model="form.growth_rate_threshold"
            :min="0"
            :max="1000"
            :step="1"
            :precision="2"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">增长率阈值（百分比），默认50.00%</span>
        </el-form-item>

        <el-form-item label="下降率阈值(%)" prop="drop_rate_threshold">
          <el-input-number
            v-model="form.drop_rate_threshold"
            :min="0"
            :max="1000"
            :step="1"
            :precision="2"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">下降率阈值（百分比），默认50.00%</span>
        </el-form-item>

        <el-form-item label="失败率阈值(%)" prop="failed_rate_threshold">
          <el-input-number
            v-model="form.failed_rate_threshold"
            :min="0"
            :max="100"
            :step="1"
            :precision="2"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">失败率阈值（百分比），默认10.00%</span>
        </el-form-item>

        <el-form-item label="心跳超时(秒)" prop="heartbeat_timeout">
          <el-input-number
            v-model="form.heartbeat_timeout"
            :min="60"
            :max="3600"
            :step="60"
            :disabled="isViewMode"
            controls-position="right"
            style="width: 100%"
          />
          <span class="form-tip">心跳超时时间（秒），默认600秒（10分钟）</span>
        </el-form-item>
      </div>

      <!-- 状态设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Setting /></el-icon>
          <span>状态设置</span>
        </div>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" :disabled="isViewMode">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="paused">暂停</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 只读信息（查看模式） -->
      <div v-if="isViewMode && queueConfig" class="form-section">
        <div class="section-title">
          <el-icon><InfoFilled /></el-icon>
          <span>运行状态</span>
        </div>

        <el-form-item label="告警状态">
          <el-tag :type="queueConfig.alert_status === 'alerting' ? 'danger' : 'success'" size="small">
            {{ queueConfig.alert_status === 'alerting' ? '告警中' : '正常' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="最新队列长度">
          <el-input :model-value="queueConfig.latest_queue_length || 0" disabled />
        </el-form-item>

        <el-form-item label="最后扫描时间">
          <el-input :model-value="queueConfig.last_scan_time || '-'" disabled />
        </el-form-item>

        <el-form-item label="最后告警时间">
          <el-input :model-value="queueConfig.last_alert_time || '-'" disabled />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-input :model-value="queueConfig.created_at || '-'" disabled />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-input :model-value="queueConfig.updated_at || '-'" disabled />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="!isViewMode"
          type="primary"
          @click="handleSubmit"
          :loading="loading"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  View, Edit, Plus, Document, InfoFilled, Bell, Setting
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('QueueConfigDialog')
const store = useRedisTaskMonitorStore()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  queueConfig: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create'
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isViewMode = computed(() => props.mode === 'view')
const isEditMode = computed(() => props.mode === 'edit')
const isCreateMode = computed(() => props.mode === 'create')

const dialogTitle = computed(() => {
  if (isViewMode.value) return '查看队列配置'
  if (isEditMode.value) return '编辑队列配置'
  return '新建队列配置'
})

const dialogDescription = computed(() => {
  if (isViewMode.value) return '查看队列监控配置详细信息'
  if (isEditMode.value) return '修改队列监控配置信息'
  return '创建新的队列监控配置'
})

const headerIcon = computed(() => {
  if (isViewMode.value) return View
  if (isEditMode.value) return Edit
  return Plus
})

const headerIconClass = computed(() => {
  if (isViewMode.value) return 'header-icon-primary'
  if (isEditMode.value) return 'header-icon-warning'
  return 'header-icon-success'
})

const envList = computed(() => store.envConfigsList)

const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  env_id: null,
  queue_key: '',
  queue_type: 'list',
  category: '',
  description: '',
  is_monitored: 1,
  is_alert_enabled: 0,
  webhook_url: '',
  alert_on_length_high: 1,
  alert_on_growth_surge: 1,
  alert_on_growth_drop: 1,
  alert_on_empty: 0,
  alert_on_failed_rate_high: 1,
  length_threshold: 1000000,
  growth_rate_threshold: 50.00,
  drop_rate_threshold: 50.00,
  failed_rate_threshold: 10.00,
  heartbeat_timeout: 600,
  status: 'active'
})

const rules = {
  env_id: [
    { required: true, message: '请选择环境', trigger: 'change' }
  ],
  queue_key: [
    { required: true, message: '请输入队列Key', trigger: 'blur' }
  ],
  queue_type: [
    { required: true, message: '请选择队列类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请输入分类', trigger: 'blur' }
  ],
  length_threshold: [
    { required: true, message: '请输入长度阈值', trigger: 'blur' },
    { type: 'number', min: 0, message: '长度阈值必须大于等于0', trigger: 'blur' }
  ],
  growth_rate_threshold: [
    { required: true, message: '请输入增长率阈值', trigger: 'blur' },
    { type: 'number', min: 0, max: 1000, message: '增长率阈值范围：0-1000', trigger: 'blur' }
  ],
  drop_rate_threshold: [
    { required: true, message: '请输入下降率阈值', trigger: 'blur' },
    { type: 'number', min: 0, max: 1000, message: '下降率阈值范围：0-1000', trigger: 'blur' }
  ],
  failed_rate_threshold: [
    { required: true, message: '请输入失败率阈值', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '失败率阈值范围：0-100', trigger: 'blur' }
  ],
  heartbeat_timeout: [
    { required: true, message: '请输入心跳超时时间', trigger: 'blur' },
    { type: 'number', min: 60, max: 3600, message: '心跳超时时间范围：60-3600秒', trigger: 'blur' }
  ]
}

// 监听queueConfig变化，填充表单
watch(() => props.queueConfig, (newVal) => {
  if (newVal) {
    Object.assign(form, {
      env_id: newVal.env_id || null,
      queue_key: newVal.queue_key || '',
      queue_type: newVal.queue_type || 'list',
      category: newVal.category || '',
      description: newVal.description || '',
      is_monitored: newVal.is_monitored !== undefined ? newVal.is_monitored : 1,
      is_alert_enabled: newVal.is_alert_enabled !== undefined ? newVal.is_alert_enabled : 0,
      webhook_url: newVal.webhook_url || '',
      alert_on_length_high: newVal.alert_on_length_high !== undefined ? newVal.alert_on_length_high : 1,
      alert_on_growth_surge: newVal.alert_on_growth_surge !== undefined ? newVal.alert_on_growth_surge : 1,
      alert_on_growth_drop: newVal.alert_on_growth_drop !== undefined ? newVal.alert_on_growth_drop : 1,
      alert_on_empty: newVal.alert_on_empty !== undefined ? newVal.alert_on_empty : 0,
      alert_on_failed_rate_high: newVal.alert_on_failed_rate_high !== undefined ? newVal.alert_on_failed_rate_high : 1,
      length_threshold: newVal.length_threshold || 1000000,
      growth_rate_threshold: newVal.growth_rate_threshold !== undefined ? newVal.growth_rate_threshold : 50.00,
      drop_rate_threshold: newVal.drop_rate_threshold !== undefined ? newVal.drop_rate_threshold : 50.00,
      failed_rate_threshold: newVal.failed_rate_threshold !== undefined ? newVal.failed_rate_threshold : 10.00,
      heartbeat_timeout: newVal.heartbeat_timeout || 600,
      status: newVal.status || 'active'
    })
  } else {
    // 重置表单
    Object.assign(form, {
      env_id: null,
      queue_key: '',
      queue_type: 'list',
      category: '',
      description: '',
      is_monitored: 1,
      is_alert_enabled: 0,
      webhook_url: '',
      alert_on_length_high: 1,
      alert_on_growth_surge: 1,
      alert_on_growth_drop: 1,
      alert_on_empty: 0,
      alert_on_failed_rate_high: 1,
      length_threshold: 1000000,
      growth_rate_threshold: 50.00,
      drop_rate_threshold: 50.00,
      failed_rate_threshold: 10.00,
      heartbeat_timeout: 600,
      status: 'active'
    })
  }
}, { immediate: true, deep: true })

// 监听对话框显示状态，加载环境列表
watch(visible, (val) => {
  if (val) {
    store.fetchEnvConfigsList()
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
})

const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    const formData = {
      env_id: form.env_id,
      queue_key: form.queue_key,
      queue_type: form.queue_type,
      category: form.category,
      description: form.description,
      is_monitored: form.is_monitored,
      is_alert_enabled: form.is_alert_enabled,
      webhook_url: form.webhook_url,
      alert_on_length_high: form.alert_on_length_high,
      alert_on_growth_surge: form.alert_on_growth_surge,
      alert_on_growth_drop: form.alert_on_growth_drop,
      alert_on_empty: form.alert_on_empty,
      alert_on_failed_rate_high: form.alert_on_failed_rate_high,
      length_threshold: form.length_threshold,
      growth_rate_threshold: form.growth_rate_threshold,
      drop_rate_threshold: form.drop_rate_threshold,
      failed_rate_threshold: form.failed_rate_threshold,
      heartbeat_timeout: form.heartbeat_timeout,
      status: form.status
    }

    if (isCreateMode.value) {
      await store.createQueueConfig(formData)
    } else if (isEditMode.value) {
      await store.updateQueueConfig(props.queueConfig.id, formData)
    }

    ElMessage.success(isCreateMode.value ? '创建成功' : '更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      // 验证失败时不显示错误消息
      componentLogger.error('提交失败', error)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.queue-config-dialog :deep(.el-dialog__header) {
  padding: 0;
}

.queue-config-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.header-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.header-icon-primary {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.header-icon-warning {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.header-icon-success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.header-content h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-content p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.queue-config-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 2px solid #ebeef5;
}

.switch-container {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.switch-description {
  flex: 1;
}

.description-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.description-text {
  margin: 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.form-tip {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>













